package xyz.app.accessors;

import lombok.NonNull;
import xyz.app.AbstractDomain;
import xyz.app.AbstractDomain_;
import xyz.app.logic.PersistenceLogic;
import xyz.app.queries.CriteriaWrapperExecute;

import java.util.Map;
import java.util.Optional;

public interface DbUpdater<T extends AbstractDomain> extends DbAccessor<T> {

    default Optional<T> update(T t, @NonNull Map<@NonNull String, Object> amendments) {

        if (null == t || t.isNew()) return Optional.empty();

        var success = new CriteriaWrapperExecute.Update<>(this)
                .set(amendments)
                .whereEqualsOrNull(AbstractDomain_.ID, t.getId()).executeUpdate();

        return success ? Optional.of(t) : Optional.empty();
    }

    default <V extends AbstractDomain> Optional<V> update(@NonNull String name, @NonNull PersistenceLogic<V> persistenceLogic) {

        var older = persistenceLogic.getInput();
        var newer = persistenceLogic.getOutput();

        var success = new CriteriaWrapperExecute.Update<>(this)
                .set(name, newer)
                .whereEqualsOrNull(name, older)
                .executeUpdate();

        return success ? Optional.of(newer) : Optional.empty();
    }
}